<template>
    <div class="alumni-built">
        <p class="catalogue">
            <router-link to="/alumni" replace>校友服务</router-link>
            <router-link :to="{path:'/alumni/news',query:{type:'cucoloris'}}" replace> > 校友剪影</router-link>
            <router-link v-if="$route.query.path == 'mine'" :to="{path:'/alumni/mine'}" replace> > 我的相册</router-link>
            <span> > 新建相册</span>
        </p>
        <div class="mine">
            <div class="mine-top clear">
                <span class="fl"><i style="color:#C74E4E">*</i>相册名称</span>
                <input class="fl" @input="setName" :disabled="disabled" @blur="checkName" v-model="name" maxlength="30" type="text" />
                <!-- <span v-if="!uploadClicked" :class="{pointer:fileList!=0,active:fileList!=0 && !uploadClicked,fl:true}" @click="uploading">开始上传</span> -->
                <span v-if="!uploadClicked" :class="{pointer:fileList!=0,active:fileList==0,fl:true}" @click="uploading">开始上传</span>
                <span v-if="uploadClicked" @click="cancelUploading" class="pointer fl">取消上传</span>
                <span class="pointer fl" v-if="fileList.length < limit && !uploadClicked">
                    <i style="font-size:20px;margin-right:10px;">+</i>添加图片<input type="file" accept="image/jpeg,image/png" @change="setUploadFile" multiple="multiple" class="upload pointer">
                </span>
            </div>
            <ul class="clear" v-if="fileList!=0">
                <!-- 每一张准备上传的图片结构，包含相册封面和删除按钮等图标 -->
                <li v-for="(item,key) in fileList" :key="key" class="fl">
                    <img :src="uploadFilesSrc[key]" alt="上传的图片" />
                    <img v-if="coverIdx==key" src="../../../assets/images/封面.png" alt="封面图标" class="coverImg" />
                    <div class="cover">
                        <p class="setCover pointer" @click="setCoverImg(key)">设为封面</p>
                        <img @click="deleteImg(key)" src="../../../assets/images/删除.png" alt="删除按钮小图标" class="close pointer" />
                    </div>

                    <!-- 正在上传时显示的上传进度封面，上传时只有取消上传的按钮能够操作，所有的图片都不能再进行设置封面和删除的操作，所有操作必须在取消上传后进行 -->
                    <div class="uploadCover" v-if="uploadClicked">
                        <div v-if="uploadProgressArr[key]>0" class="clear">
                            <span class="fl"><i class="fl" :style="{width:uploadProgressArr[key]+'%'}"></i></span>
                            <span class="fr">{{uploadProgressArr[key]}}%</span>
                        </div>
                        <div v-if="!uploadProgressArr[key]" v-loading="true" element-loading-text="等待上传" element-loading-spinner="el-icon-loading" class="waiting" style="background:transparent;"></div>
                    </div>
                </li>
            </ul>
            <div class="empty" v-if="fileList==0">最多添加{{limit}}张相片哦~</div>

            <!-- 饿了么上传插件 -->
            <!-- <el-upload
                class="uploader"
                :action="uploaderURL"
                :on-preview="handlePreview"
                :on-remove="handleRemove"
                :before-remove="beforeRemove"
                multiple
                :headers="headers"
                :limit="limit"
                :on-exceed="handleExceed"
                list-type="picture"
                :file-list="fileList">
                <el-button size="medium" type="warning"><i style="font-size:20px;margin-right:10px;">+</i>添加图片</el-button>
            </el-upload> -->


            <!-- vue-simple-uploader插件 -->
            <!-- <uploader :options="options" class="uploader-example">
                <uploader-unsupport></uploader-unsupport>
                <uploader-drop>
                    <p>Drop files here to upload or</p>
                    <uploader-btn>select files</uploader-btn>
                    <uploader-btn :attrs="attrs">select images</uploader-btn>
                    <uploader-btn :directory="true">select folder</uploader-btn>
                </uploader-drop>
                <uploader-list></uploader-list>
            </uploader> -->
        </div>
        <div class="finish" v-if="uploadFinish">
            <div>
                <div class="finish-top clear">提示<img @click="closeBuildPage" class="fr pointer" src="../../../assets/images/删除.png" alt="关闭小图标" /></div>
                <div class="finish-main">
                    <p>上传成功，请耐性等待管理员审核</p>
                    <button class="pointer" @click="closeBuildPage">好的</button>
                </div>
            </div>
        </div>
    </div>
</template>

<script>
import Global from '../../../tools/global.js'; // 引入global.js
export default {
	data(){
		return {
            name:'',    // 新建相册的名字
            uploaderURL:this.BASE_URL + '/appapi/resource/res_upload',     // 上传地址
            limit:20,    // 限制上传的数量
            disabled:false,      // 当点击开始上传时值为true，禁止修改名称
            coverIdx:0,     // 设为封面的数组id，若不设置默认第一张为封面 
            fileList:[],     // 用于存放上传图片的数组
            uploadFilesSrc:[],     // 存放已选上传图片的base64格式的URL 
            uploadClicked:false,    // 当点解开始上传时，此值改为true;
            uploadCompleteURL:[],     // 存放上传成功后返回的后台地址
            uploadProgressArr:[],     // 开始上传时用于存放上传进度的百分比
            uploadFinish:false,     // 此参数当所有图片都成功上传完之后变为true
            headers:{     // 请求头信息
                Authorization:`Bearer ${Global.access_token}`,
                DecisionPlatform: sessionStorage.getItem('decisionPlatform'),
                token:localStorage.getItem('logintoken') == '--' ? null : localStorage.getItem('logintoken')
            }
		}
	},
    created(){
        
    },
	methods:{
        // 输入名字的方法imagic
        setName(){
            var sum = this.name.length;

            if(sum>30){
                // this.$message.closeAll();
                this.$message.error('最多输入30个字符');

                this.name = this.name.slice(0,30);
            }
        },
        // 失焦时检查输入的名字是否为空或者纯空格
        checkName(){
            this.name = this.name.trim();
        },
        // 设置封面图片
        setCoverImg(idx){
            this.coverIdx = idx;
        },
        // 删除已选中图片
        deleteImg(idx){
            // console.log(this.uploadFilesSrc,this.fileList)
            this.fileList.splice(idx,1);
            this.uploadFilesSrc.splice(idx,1);
            // console.log(this.uploadFilesSrc,this.fileList)

            // 如果删除图片为封面图片则重置封面图片
            if(this.coverIdx==idx){
                this.coverIdx = 0;
            }else if(this.coverIdx>idx){
                this.coverIdx -=1 
            }
        },
        // 对选择上传图片的操作方法
        setUploadFile(){
            // 获取上传的DOM节点
            var upload = document.querySelector('.upload');

            // 获取选择上传文件信息数组
            var uploadArr = Array.from(upload.files);

            // 项目要求只能上传image/jpeg和image/png,去除这两种格式意外的文件
            // 声明一个变量用于存放根式不符合的文件数量
            var formatError = 0;    

            // 声明一个变量用于存放符合要求的文件数组
            var fileArr = uploadArr.filter(item=>{
                if(item.type=='image/jpeg' || item.type=='image/png'){
                    return item
                }else{
                    formatError++
                }

            })

            // 如果存在不符合格式的文件则报错
            if(formatError>0){
                // this.$message.closeAll();
                this.$message.error( `一共有${formatError}个文件格式不符,已经自动过滤`);
            }

            var sum = this.fileList.length + fileArr.length;

            if(sum > this.limit){
                // this.$message.closeAll();
                this.$message.error(`最多只能上传${this.limit}张图片`);

            }else{
                this.fileList = [...this.fileList,...fileArr]
                // console.log(this.fileList)

                // 获取到最新已选图片后重置uploadFilesSrc并存入最新的base64格式URL
                this.uploadFilesSrc = [];
                this.fileList.forEach(item=>{
                    this.getImgURL(item);
                })
            }

        },
        // 上传请求 （可以在这里或则getImgURL进行图片压缩的操作）
        uploading(){
            // 如果没有上传的文件和没有名字则无任何操作并提醒
            if(this.fileList==0){
                // this.$message.closeAll();
                this.$message.error('请选择上传图片');
                return
            }else if(!this.name){
                // this.$message.closeAll();
                this.$message.error('请输入相册名称');
                return
            }

            // 隐藏添加图片按钮
            this.uploadClicked = true;

            // 禁止修改相片名称
            this.disabled = true;

            // 以下一行代码在同时发送上传请求时才有用
            // this.uploadProgressArr = this.fileList.map(function(){return 0});
            // 检测之前有没有经上传好的图片，若没有则新建一个跟uploadProgressArr长度一样的空数组
            if(this.uploadCompleteURL==0){
                this.uploadCompleteURL = this.fileList.map(function(){return ''});
            }
            // 若已经存在上传完的图片，则在保留已上传的图片基础上增加新的空元素，使数组长度跟uploadProgressArr长度一直
            else{
                var emptyArr = this.fileList.map(function(){return ''});
                this.uploadCompleteURL = [...this.uploadCompleteURL,...emptyArr].slice(0,this.fileList.length)
            }

            // 以下3行注释为同时发送上传请求的操作
            // this.fileList.forEach((item,idx)=>{
                // this.uploadProgress(item,idx)
            // })
            
            // 以下为逐张图片上传的操作,先从第一张没有上传完的图片开始，每当上传完一张出发下一张上传
            var idx = 'full';     // full 代表数组里没有空的元素（全部图片已上传）
            // console.log(this.uploadCompleteURL)
            for(var i=0;i<this.uploadCompleteURL.length;i++){
                if(!this.uploadCompleteURL[i]){
                    idx = i;
                    break;
                }
            }

            // console.log('idx:',idx)
            if(idx=='full'){
                // 若全部图片已上传完则之间发起新建相册请求
                this.buildPhotograph();
            }else{

                this.uploadProgressArr = this.uploadCompleteURL.map(item=>{if(item){return 100}else{return 0}});

                this.uploadProgress(this.fileList[idx],idx)
            }
            
        },
        // 取消上传请求
        cancelUploading(){
            // console.log('取消上传请求')
            if(this.source){
                this.source.cancel('Operation canceled by the user.');
            }
            // console.log(this.fileList,
            //             this.uploadFilesSrc,
            //             this.uploadCompleteURL,
            //             this.uploadProgressArr)

            // 遍历已经上传的图片数组，获取到第一个空值的索引值
            for(var i=0;i<this.uploadCompleteURL.length;i++){
                if(!this.uploadCompleteURL[i]){
                    var idx = i;
                    break;
                }
            }

            // 允许修改相片名称
            this.disabled = false;

            // 把还没有上传完的图片删掉
            this.fileList = this.fileList.slice(0,idx);
            this.uploadFilesSrc = this.uploadFilesSrc.slice(0,idx);
            this.uploadCompleteURL = this.uploadCompleteURL.slice(0,idx);
            this.uploadProgressArr = this.uploadProgressArr.slice(0,idx);
            
            // console.log('uploadCompleteURL:',this.uploadCompleteURL)
            // console.log('uploadProgressArr:',this.uploadProgressArr)

            this.uploadClicked = false;
        },
        // 上传的进度检测方法
        uploadProgress(blod,key){
            // 创建取消请求令牌
            var CancelToken = this.$ajax.CancelToken;
            this.source = CancelToken.source();

            var formdata=new FormData();

            formdata.append('file',blod);

            let success = res => {
                function getData(data){
                    return data.data ? getData(data.data) : data;
                }

                let data = getData(res);

                this.uploadProgressArr[key] = 100;
                this.uploadCompleteURL[key] = {pic:data.file_path,cover:0};
                // 以下三行为更新数据操作
                var finish = this.uploadProgressArr;
                this.uploadProgressArr = '';
                this.uploadProgressArr = finish;
                // console.log(this.uploadProgressArr)

                // 此为逐张图片上传的方法
                // 每次上传完都先检测是不是最后一张图片，若是自动发起新建相册请求，反则发起下一张图片的上传请求
                if(key==this.fileList.length-1){
                    this.buildPhotograph()
                }else{
                    this.uploadProgress(this.fileList[key+1],key+1)
                }

                // 以下为全部图片同时上传的方法
                // var arr = this.uploadCompleteURL
                // for(var i=0;i<arr.length;i++){
                //     if(!arr[i]){
                //         return
                //     }
                // }
                // // 如果uploadProgressArr所有元素都变为object则发送新建相册请求
                // this.buildPhotograph()
            }

            // console.log(formdata.get('file'))
            this.$ajax({
                url:'/api/resource/res_upload',
                method:'post',
                data:formdata,
                headers:{'content-type':'multipart/form-data'},
                cancelToken: this.source.token,
                onUploadProgress:progressEvent=>{ //原生获取上传进度的事件
                    if(progressEvent.lengthComputable){
                        //属性lengthComputable主要表明总共需要完成的工作量和已经完成的工作是否可以被测量
                        //如果lengthComputable为false，就获取不到progressEvent.total和progressEvent.loaded
                        var percent = parseInt(progressEvent.loaded/progressEvent.total*100);

                        this.uploadProgressArr[key] = percent>=100? 99 : percent;
                        // 以下三行为更新数据操作
                        var arr = this.uploadProgressArr;
                        this.uploadProgressArr = '';
                        this.uploadProgressArr = arr;

                        // console.log('uploadCompleteURL:',this.uploadCompleteURL)
                        // console.log('uploadProgressArr:',this.uploadProgressArr)
                    }
                },
                func: { success: success }
            })
            // 此为避免报错操作
            .catch(function (error) {});

        },
        // 发送新建相册请求
        buildPhotograph(){
            // console.log(this.uploadCompleteURL,this.name)

            // 获取登录用户的id
            var id = JSON.parse(sessionStorage.getItem('user_info_str')).id;
            let success = res => {
                // console.log(res.data)
                this.uploadFinish = true;
            }

            // 等最后可以发送新建相册时再确定封面图片，避免上传中断后出现重选封面图片再上传的情况
            this.uploadCompleteURL[this.coverIdx].cover = 1;

            this.$ajax({
                url:'/api/alumni/alumniPic',
                method:'post',
                data:{
                    name:this.name,     // 名
                    pic_arr:this.uploadCompleteURL,     // 图片，二维数组【【'pic'=>'/home/picture.jpg','cover' =>1】】（键名：pic:图片地址；cover 封面标志（0：否；1：是））
                    create_id:id     // 创建人id
                },
                func: { success: success }
            })

        },
        // 图片上传完之后点击确认或者关闭都返回上一级页面
        closeBuildPage(){
            if(this.$route.query.path == 'mine'){
                this.$router.back()
            }else{
                this.$router.replace('/alumni/mine');
            }
        },
        // 上传图片格式转换为base64格式的方法（可以在这里或则uploading进行图片压缩的操作）
        getImgURL(file){
            var arr = this.uploadFilesSrc;

            var src;

            var reader = new FileReader();

            reader.addEventListener("load", function () {
                src = this.result;
                arr.push(src)
            }, false);

            reader.readAsDataURL(file);

        },
        // 饿了么上传组件的相关方法
        // handleRemove(file, fileList) {
        //     console.log(file, fileList);
        // },
        // handlePreview(file) {
        //     console.log(file);
        // },
        // handleExceed(files, fileList) {
        //     this.$message.warning(`当前限制选择 ${this.limit} 个文件，本次选择了 ${files.length} 个文件，共选择了 ${files.length + fileList.length} 个文件`);
        // },
        // beforeRemove(file, fileList) {
        //     return this.$confirm(`确定移除 ${ file.name }？`);
        // },
	},
}
</script>


<style lang="scss">
    #alumni{
        .alumni-built{
            margin:0 auto 62px;
            width:1202px;
            // 目录
            .catalogue{
                height:19px;
                line-height:19px;
                font-size: 14px;
                color: #000000;
                letter-spacing: 0;
                span{
                    &:nth-child(2){
                        color: #3F3F3F;
                    }
                    &:last-child{
                        color: #333333;
                    }
                }
            }
            .mine{
                margin-top:20px;
                width:100%;
                background:#fff url("../../../assets/images/image06.png") center top no-repeat;
                overflow:hidden;
                .mine-top{
                    // background: pink;
                    margin:170px 99px 0;
                    // width:100%;
                    height:48px;
                    line-height:48px;
                    text-align:center;
                    span{
                        margin-top:6px;
                        height:36px;
                        line-height:36px;
                        letter-spacing: 0;
                        &:first-child{
                            font-size: 18px;
                            color: #000000;
                        }
                        &:nth-child(3){
                            margin-left:20px;
                            width:96px;
                            font-size: 14px;
                            color: #FFFFFF;
                            background: #348EFC;
                            border-radius: 3px;
                            &.active{
                                background: #CECECE;
                            }
                        }
                        &:nth-child(4){
                            position:relative;
                            margin-left:20px;
                            width:122px;
                            line-height:32px;
                            font-size: 14px;
                            color: #FFFFFF;
                            background: #E9AB30;
                            border-radius: 3px;
                            overflow:hidden;
                            input{
                                position:absolute;
                                z-index:1;
                                top:0;
                                left:0;
                                width:100%;
                                height:100%;
                                opacity:0;
                            }
                        }
                    }
                    &>input{
                        margin-left:20px;
                        padding:0 28px;
                        width:582px;
                        height:46px;
                        line-height:46px;
                        font-size: 18px;
                        color: #000000;
                        letter-spacing: 0;
                        border: 1px solid #E0E0E0;
                    }
                }
                &>ul.clear{
                    margin:53px 0 45px 41px;
                    li{
                        position:relative;
                        margin:0 20px 18px 0;
                        width:360px;
                        height:240px;
                        overflow:hidden;
                        &>img{
                            width:100%;
                            height:100%;
                            object-fit:cover;
                            &.coverImg{
                                position:absolute;
                                top:0;
                                left:0;
                                width:44px;
                                height:44px;
                            }
                        }
                        .cover{
                            display:none;
                            position:absolute;
                            top:0;
                            left:0;
                            width:100%;
                            height:100%;
                            background: rgba(0,0,0,0.5);
                            p{
                                margin:102px auto;
                                width:120px;
                                height:36px;
                                line-height:36px;
                                border-radius: 4px;
                                font-size: 14px;
                                color: #FFFFFF;
                                letter-spacing: 0;
                                text-align:center;
                                background: #348EFC;
                            }
                            .close{
                                position:absolute;
                                top:14px;
                                right:13px;
                                width:16px;
                                height:16px;
                            }
                        }
                        .uploadCover{
                            // pointer-events:none;
                            // display:none;
                            position:absolute;
                            top:0;
                            left:0;
                            width:100%;
                            height:100%;
                            background: rgba(0,0,0,0.5);
                            &>div.clear{
                                margin:111px auto 0;
                                padding:0 55px;
                                height:19px;
                                text-align:center;
                                &>span{
                                    &:first-child{
                                        margin-top:2px;
                                        width:200px;
                                        height:8px;
                                        text-align:left;
                                        background: #0B1136;
                                        i{
                                            height:8px;
                                            background: #33BBBB;
                                        }
                                    }
                                    &:last-child{
                                        font-size: 14px;
                                        color: #FFFFFF;
                                        letter-spacing: 0;
                                    }
                                }
                            }
                            .waiting{
                                height:100%;
                                .el-loading-mask{
                                    background: transparent;
                                    .el-loading-spinner{
                                        .el-icon-loading{
                                            font-size:22px;
                                            color:#fff;
                                        }
                                        .el-loading-text{
                                            margin-top:13px;
                                            font-size: 14px;
                                            color: #FFFFFF;
                                            letter-spacing: 0;
                                        }
                                    }
                                }
                            }
                        }
                        &:hover .cover{
                            display:block;
                        }
                    }
                }
                .empty{
                    box-sizing:border-box;
                    width:100%;
                    height:603px;
                    padding-top:386px;
                    background: url("../../../assets/images/image05.png") center 148px no-repeat;
                    font-size: 16px;
                    color: #A2B2BB;
                    text-align:center;
                    letter-spacing: 0;
                }
                .uploader{
                    .el-upload{

                        el-button{
                            margin-left:20px;
                            width:122px;
                            font-size: 14px;
                            color: #FFFFFF;
                            background: #E9AB30;
                            border-radius: 3px;
                        }
                    }
                    .el-upload-list--picture{
                        .el-upload-list__item{
                            float:left;
                            margin:0 20px 18px 0;
                            padding:0;
                            width:360px;    
                            height:240px;   
                            overflow:hidden;    
                            .el-upload-list__item-name{
                                display:none;
                            }
                            .el-upload-list__item-thumbnail{
                                width:100%;
                                height:100%;
                                object-fit:cover;
                                margin:0;
                            }
                        }
                    }
                }
            } 
            .finish{
                position:fixed;
                z-index:20;
                top:0;
                left:0;
                width:100%;
                height:100%;
                background: rgba(0,0,0,0.5);
                &>div{
                    margin:290px auto 0;
                    width:400px;
                    height:240px;
                    .finish-top{
                        padding-left:20px;
                        height:36px;
                        line-height:36px;
                        font-size: 14px;
                        color: #FFFFFF;
                        letter-spacing: 0;
                        background: #348EFC;
                        img{
                            width:16px;
                            height:16px;
                            object-fit:cover;
                            margin-top:10px;
                            margin-right:10px;
                        }
                    }
                    .finish-main{
                        height:204px;
                        background: #fff;
                        p{
                            margin:0 auto;
                            padding-top:75px;
                            height:19px;
                            line-height:19px;
                            font-size: 14px;
                            color: #000000;
                            letter-spacing: 0;
                            text-align: center;
                        }
                        button{
                            display:block;
                            margin:61px auto 0;
                            width:68px;
                            height:30px;
                            font-size: 14px;
                            color: #FFFFFF;
                            letter-spacing: 0;
                            text-align:center;
                            background: #348EFC;
                            border-radius: 3px;
                            border-style:none;
                        }
                    }
                }
            }
        }
    }
</style>